import time
import traceback

import pymysql
import urllib3
import requests
from jsonpath import jsonpath
from requests_toolbelt import MultipartEncoder


from Common.CusMethod import random_letter, random_str, random_time
from Common.DataHandle import ReRun
from Common.FontColor import outcome
from Common.MyUnit import MyTest
from Common.ReExecution import NumberCycles
from Common.ReadWriteIni import ReadWrite
from Common.ReadYaml import ConfigYaml, ReadKeyWorld, ReadPublic
from Common.Login import Login
from Common.Route import Any_Path

class GoodsRelatedData:


    def __init__(self):
        """
        关于产品模块相关功能数据类接口
        """
        self.login = Login
        self.base_url = ConfigYaml('domain_name').base_url
        self.login_job_url = ConfigYaml('job-manager').base_url
        self.token_key = ConfigYaml('token_key').base_config
        self.token_value = ReadWrite().read_ini_token()
        self.headers = {self.login.content_type_key: self.login.content_json_type_value,
                        self.token_key: self.token_value}
        self.dir = "goods"
        # self.warehose_name = ConfigYaml('wawarehouse_name').base_config
        # self.matching_world = ConfigYaml('matching_world').base_config
        # self.channel_name = ConfigYaml('channle_name').base_config
        self.key_world = ReadKeyWorld(catalog="goods")
        # self.qa_host = ConfigYaml('testsql_host').base_config
        # self.qa_port = ConfigYaml('testsql_port').base_config
        # self.qa_user = ConfigYaml('testsql_user').base_config
        # self.qa_pwd = ConfigYaml('testsql_pwd').base_config
        # self.db = ConfigYaml('erp_goods_operation').base_config
        # self.login.write_token
    @NumberCycles(2)
    def add_plm_product(self):
        """
        创建plm产品
        :return:
        """
        try:
            public_data = ReadPublic(catalog=self.dir, key="add_product")
            url = self.base_url + public_data.public_value("url")
            category_id_list = self.get_category_list()
            category_id = ''.join(category_id_list).split(',', 3)[3]
            supplier_Name = ReadKeyWorld(catalog=self.dir).key_world_value("supplierName")
            supplier_Id = self.get_supplier(name=supplier_Name).get("supplierId")
            random = random_time()
            data = public_data.public_value("bar")
            data["basic"]["categoryId"] = category_id
            data["basic"]["code"] = self.get_spu(category_id)
            data["basic"]["name"]="自动化测试"
            data["basic"]["supplierId"] = supplier_Id
            data["basic"]["supplierName"] = supplier_Name
            data["basic"]["supplierItemNo"] = random
            data["basic"]["choseBy"] = 932
            data["basic"]["choseByName"] = "补旭东"
            data['variantPlate']['supplierName'] = data["basic"]["supplierName"]
            data['variantPlate']["supplierId"] = supplier_Id
            r = requests.post(url, headers=self.headers, json=data, stream=True, verify=False).json()
            return  r, data
        except:
            self.singulay = str(traceback.format_exc())
            outcome('red', self.singulay)
            return self.singulay

    @NumberCycles(2)
    def get_category_list(self, switch=False):
        """
        获取品类列表
        :return:
        """
        public_data = ReadPublic(catalog=self.dir, key="get_category_list")
        url = self.base_url + public_data.public_value("url")
        #data = public_data.public_value("bar")
        category_list = []
        r = requests.get(url, headers=self.headers, stream=True, verify=False)
        result = jsonpath(r.json(), "$.data[?(@.name == '自动化专属分类')]..[?(@.levelPath.length > 25)].levelPath")
        if result:
            return result
        else:
            self.add_plm_category(name="自动化专属分类")

    def add_plm_category(self, name=''):
        """
        添加plm品类
        :param switch:
        :return:
        """
        public_data = ReadPublic(catalog=self.dir, key="add_plm_category")
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        if name:
            category_name = name
        else:
            category_name = random_str(ReadKeyWorld(catalog=self.dir).key_world_value("category_name"))
        for index in range(4):
            if index == 3:
                category_code = random_letter(6)
            else:
                category_code = random_letter()
            data["name"] = category_name
            data["code"] = category_code
            data["parentId"] = parent_id
            r = requests.post(url, headers=self.headers, json=data, stream=True, verify=False)
            result = r.json()
            if result["success"]:
                category_id = result["data"]["id"]
                parent_id = category_id
            elif "重复" in result["error"]["message"]:
                return self.add_plm_category(parent_id=parent_id)

    @NumberCycles(2)
    def get_attributes(self):
        """获取颜色主属性"""
        public_data = ReadPublic(catalog=self.dir, key="get_attribute")
        url = self.base_url + public_data.public_value("url")
        r = requests.get(url, headers=self.headers, stream=True, verify=False)
        result = r.json()
        if result['success']:
            result_srt = jsonpath(r.json(), "$..list[?(@.name == '颜色')]")[0]
            attribute_id = result_srt.get("id")
            return attribute_id

    @NumberCycles(2)
    def add_attribute_to_category(self, category_id='', attribute_id=''):
        """
        为新增品类增加属性
        :return:
        """

        category_id_list = self.get_category_list()
        if category_id:
            categoryId = category_id
        else:
            categoryId = ''.join(category_id_list).split(',', 3)[0]
        if attribute_id:
            attributeId = attribute_id
        else:
            attributeId = self.get_attributes()
        public_data = ReadPublic(catalog=self.dir, key="add_attribute_to_category")
        url = self.base_url + public_data.public_value("url").format(categoryId)
        data = public_data.public_value("bar")
        data["attributeIds"] = [attributeId]
        r = requests.post(url, headers=self.headers, json=data, stream=True, verify=False)
        result = r.json()
        return r, data

    @NumberCycles(2)
    def get_spu(self, category_id=''):
        """
        获取spu
        :param category_id:
        :return:
        """
        if category_id:
            categoryId = category_id
        else:
            category_id_list = self.get_category_list()
            categoryId = ''.join(category_id_list).split(',', 3)[3]
        public_data = ReadPublic(catalog=self.dir, key="get_spu")
        url = self.base_url + public_data.public_value("url").format(categoryId)
        r = requests.get(url, headers=self.headers, stream=True, verify=False)
        result = r.json()
        return result['data']

    @NumberCycles(2)
    def get_supplier(self, name=''):
        """获取各供应商信息"""
        if name:
            supplierName = name
        else:
            supplierName = ReadKeyWorld(catalog=self.dir).key_world_value("supplierName")
        public_data = ReadPublic(catalog=self.dir, key="get_supplier")
        url = self.base_url + public_data.public_value("url").format(supplierName)
        r = requests.get(url, headers=self.headers, stream=True, verify=False)
        result = r.json()
        supplier_info = result['data']['list'][0]
        if supplier_info:
            return supplier_info
        else:
            self.add_supplier("自动化专属供应商")

    @NumberCycles(2)
    def infringement_review(self):
        """
        侵权风险审核
        :param spu:
        :return:
        """
        product_info=self.get_product_detail()
        spu_code = product_info['data']['code']
        public_data = ReadPublic(catalog=self.dir, key="infringement_review")
        url = self.base_url + public_data.public_value("url").format(spu_code)
        data = public_data.public_value("bar")
        r = requests.post(url, headers=self.headers, json=data, stream=True, verify=False).json()
        return r, product_info

    @NumberCycles(2)
    def sample_to_auditor(self):
        """提交验样"""
        infringement_review_list=self.infringement_review()
        spu_code = infringement_review_list[1]['data']['request']['basic']['code']
        category_id = infringement_review_list[1]['data']['request']['basic']['categoryId']
        sku_code = infringement_review_list[1]['data']['request']['variantPlate']['variants'][0]['skuCode']
        public_data = ReadPublic(catalog=self.dir, key="sample_to_auditor")
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['basic']['categoryId'] = category_id
        data['basic']['categoryName']
        data['basic']['code'] = spu_code
        data['variantPlate']['variants'][0]['skuCode'] = sku_code
        r = requests.post(url, headers=self.headers, json=data, stream=True, verify=False).json()
        return r, data

    @NumberCycles(2)
    def get_product_detail(self):
        """获取sku的侵权商品详情"""
        product_list = self.add_plm_product()
        productId = product_list[0]['data']['productDraftId']
        public_data = ReadPublic(catalog=self.dir, key="get_product_detail")
        url = self.base_url + public_data.public_value("url").format(productId)
        r = requests.get(url, headers=self.headers, stream=True, verify=False).json()
        return r

    @NumberCycles(2)
    def sample_check(self):
        """产品验样,"""
        sample_to_auditor_info = self.sample_to_auditor()
        spu_code = sample_to_auditor_info[1]['basic']['code']
        public_data = ReadPublic(catalog=self.dir, key="sample_check")
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['codes'] = [spu_code]
        r = requests.post(url, headers=self.headers, json=data, stream=True, verify=False).json()
        return r, sample_to_auditor_info[1]

    @NumberCycles(2)
    def product_publish(self):
        """产品发布至产品库,前置条件产品验样通过后"""
        sample_check_info = self.sample_check()
        spu_code = sample_check_info[1]['basic']['code']
        category_id = sample_check_info[1]['basic']['categoryId']
        supplier_id = sample_check_info[1]['basic']['supplierId']
        supplierItemNo = sample_check_info[1]['basic']['supplierItemNo']
        skuCode = sample_check_info[1]['variantPlate']['variants'][0]['skuCode']
        public_data = ReadPublic(catalog=self.dir, key='product_publish')
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['basic']['categoryId'] = category_id
        data['basic']['code'] = spu_code
        data['basic']['supplierId'] = supplier_id
        data['basic']['supplierItemNo'] = supplierItemNo
        data['variantPlate']['variants'][0]['skuCode'] = skuCode
        r = requests.post(url, headers=self.headers, json=data, stream=True, verify=False).json()
        return r, data

    @NumberCycles(2)
    def queryParameter(self, replenishmentType='0'):
        '''
        查询备货参数列表
        replenishmentType=0不备货，1，静态备货，2.动态备货
        supplierCategory： 0. ODM   1. OEM
        '''
        warehouseId = self.warehouse_list()['id']
        public_data = ReadPublic(catalog=self.dir, key='queryParameter')
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['warehouseId'] = 185
        data['replenishmentType'] = replenishmentType
        # data['supplierCategory'] = supplierCategory
        r = requests.get(url, headers=self.headers, params=data, stream=True, verify=False).json()
        return r

    def query_sourceType(self, sourceType=2):
        """
        备货参数货源类型查询
        sourceType=2默认的供应商推品
        """
        warehouseId = self.warehouse_list()['id']
        public_data = ReadPublic(catalog=self.dir, key='query_sourceType')
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['warehouseId'] = 185
        data['sourceType'] = sourceType
        r = requests.get(url, headers=self.headers, params=data, stream=True, verify=False)
        return r



    @NumberCycles(2)
    def warehouse_list(self):
        """查询仓库列表"""
        public_data = ReadPublic(catalog=self.dir, key='warehouse_list')
        url = self.base_url + public_data.public_value("url")
        r = requests.get(url, headers=self.headers, stream=True, verify=False).json()
        result = jsonpath(r, "$..list[?(@.name == '自动化专属仓库')]")[0]
        return result

    @NumberCycles(2)
    def updateParameter(self, replenishmentType='0'):
        """
        编辑提交静态备货参数
        replenishmentType ：0.不备货，1.静态备货，2.动态备货
        supplierCategory:  0. ODM，  1. OEM
        """
        ptype = replenishmentType
        #supplier = supplierCategory
        query_list = self.queryParameter()['data']['list'][0]
        id = query_list['id']
        public_data = ReadPublic(catalog=self.dir, key='updateParameter')
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data["id"] = id
        r = requests.post(url, headers=self.headers, json=data, stream=True, verify=False)
        return query_list


    # def job_manager_login(self):
    #     """登录定时任务"""
    #     public_data = ReadPublic(catalog=self.dir, key='job_manager_login')
    #     url = self.login_job_url + public_data.public_value("url")
    #     #data = public_data.public_value("bar")
    #     r = requests.post(url, stream=True, verify=False)
    #     cookies = r.cookies
    #     cookie = requests.utils.dict_from_cookiejar(cookies)
    #     return cookie

    # def job_to_requisition_review(self, jobid='23'):
    #     """
    #     启动需求计算任务，将备货参数列表数据同步至检核工作台（待检核列表）
    #     jobid: 18	清洗订单信息任务
    #         19  计算销量任务
    #         20  计算未发货量任务
    #         21  需求检核工作台（待检核-->超时未处理）
    #         22  需求检核工作台（已检核-->采购需求）
    #         23. 启动需求计算任务(qa环境23， beta环境25）
    #     """
    #     cookie = self.job_manager_login()
    #     id = jobid
    #     public_data = ReadPublic(catalog=self.dir, key="job_to_requisition_review")
    #     url = self.login_job_url + public_data.public_value("url")
    #     data = public_data.public_value("bar")
    #     data['id'] = id
    #     r = requests.post(url, cookies=cookie, params=data, stream=True, verify=False).json()
    #     return r

    # @NumberCycles(2)
    # def get_review_list(self, replenishmentType='1'):
    #     """检核工作台列表, 返回静态备货，odm的列表
    #     replenishmentType=0 表示不备货， 1. 静态备货， 2.动态备货
    #     supplierCategory=0 表示ODM， supplierCategory=1 表示OEM
    #     """
    #     parameter = self.updateParameter(replenishmentType)
    #     sku_code = parameter['skuCode']
    #     GoodsRelatedData().job_to_requisition_review(jobid='23')  # 执行定时任务
    #     time.sleep(60)
    #     public_data = ReadPublic(catalog=self.dir, key="get_review_list")
    #     url = ConfigYaml("domain_name").base_url + public_data.public_value("url")
    #     data = public_data.public_value("bar")
    #     data['warehouseId'] = 185
    #     data['skuCodes'] = sku_code
    #     data['replenishmentType'] = replenishmentType
    #     # data['supplierCategory'] = supplierCategory
    #     r = requests.get(url, headers=self.headers, params=data, stream=True, verify=False).json()
    #     return r


    # def submitRequisitionReview(self, num=0):
    #     """
    #     待检核数据提交已检核
    #     num参数表示需修改的最终确认量，默认0，不修改，则进入已检核未调整，
    #     num不为0表示需要修改多少，修改后进入已检核已调整列表
    #     """
    #     if num != 0:
    #         save_final = self.save_finalConfirmation()
    #         id = save_final[1]['id']
    #         finalConfirmation = save_final[1]['finalConfirmation']
    #         sku = save_final[0]
    #     else:
    #         review_list = self.get_review_list(1)
    #         id = review_list['data']['list'][0]['id']
    #         finalConfirmation = review_list['data']['list'][0]['finalConfirmation']
    #         sku = review_list['data']['list'][0]['skuCode']
    #     public_data = ReadPublic(catalog=self.dir, key="submitRequisitionReview")
    #     url = self.base_url + public_data.public_value("url")
    #     data = public_data.public_value("bar")
    #     data[0]['finalConfirmation'] = finalConfirmation
    #     data[0]['id'] = id
    #     r = requests.put(url, headers=self.headers, json=data, stream=True, verify=False).json()
    #     return sku, data

    # def save_finalConfirmation(self):
    #     """
    #     编辑待检核列表中确认需求量
    #     add_num需要增加的需求量
    #     :return:
    #     """
    #     add_num = 5
    #     review_list = self.get_review_list(1)
    #     id = review_list['data']['list'][0]['id']
    #     finalConfirmation = review_list['data']['list'][0]['finalConfirmation']
    #     sku = review_list['data']['list'][0]['skuCode']
    #     public_data = ReadPublic(catalog=self.dir, key="save_finalConfirmation")
    #     url = self.base_url + public_data.public_value("url")
    #     data = public_data.public_value("bar")
    #     num = finalConfirmation + add_num
    #     data['finalConfirmation'] = num
    #     data['id'] = id
    #     r = requests.put(url, headers=self.headers, json=data, stream=True, verify=False).json()
    #     return sku, data

    def purchase_list(self, purchase_status=0, sku=""):
        """
        采购需求列表中待采购查询
        purchase_status=0 表示待采购，purchase_status=1表示待下单
        :return:
        """

        public_data = ReadPublic(catalog=self.dir, key="purchase_list")
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['warehouseId'] = 185
        data['purchaseRequisitionStatus'] = purchase_status
        data['skuCodes']= sku
        r = requests.get(url, headers=self.headers, params=data, stream=True, verify=False)
        return r

    def batchGenerate_by_ids(self):
        """
        生成采购计划
        :return:
        """
        purchase_list = self.purchase_list().json()
        id = purchase_list['data']['list'][0]['id']
        sku = purchase_list['data']['list'][0]['skuCode']
        public_data = ReadPublic(catalog=self.dir, key="batchGenerate_by_ids")
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data = [id]
        r = requests.post(url, headers=self.headers, json=data, stream=True, verify=False)
        return r, sku


    def replenishment_import(self):
        """
        备货参数导入
        """
        dir = "Export"
        files = "replenishment_export_by_sku.xlsx"
        excel_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        public_data = ReadPublic(catalog=self.dir, key="replenishment_import")
        url = self.base_url + public_data.public_value("url")
        file_path = Any_Path(dir, files)
        f = open(file_path, 'rb')
        m = MultipartEncoder(
            fields={'filename': file_path,
                    'file': (files, f, excel_type)})

        headers = {
            "Authorization": ReadWrite().read_ini_token(),
            "Content-Type": m.content_type
        }
        r = requests.post(url, headers=headers, data=m)
        f.close()
        return r

    def supplier_sku_relation(self):
        """采购管理中 sku与供应商关系查询
        返回defaultRelationId, skuId, supplierId, supplierProductNo
        """
        source_list = self.query_sourceType(sourceType=2).json()
        sku = source_list['data']['list'][0]['skuCode']
        public_data = ReadPublic(catalog=self.dir, key="supplier_sku_relation")
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['typeValue'] = sku
        r = requests.get(url, headers=self.headers, params=data, stream=True, verify=False)
        return r

    def get_supplierInfo(self):
        """
        根据supplier_sku_relation返回的defaultRelationId，
        查询sku对应的供应商信息
        """
        relation_list = self.supplier_sku_relation().json()
        relationId = relation_list['data']['list'][0]['defaultRelationId']
        public_data = ReadPublic(catalog=self.dir, key="get_supplierInfo")
        url = self.base_url + public_data.public_value("url").format(relationId)
        r = requests.get(url, headers=self.headers, stream=True, verify=False)
        return r

    def update_supplierInfo(self):
        """
        提交修改供应商交期的值
        依赖get_supplierInfo返回的值
        """
        supplierInfo_res = self.get_supplierInfo().json()
        id = supplierInfo_res['data']['id']
        skuId = supplierInfo_res['data']['skuId']
        sku = supplierInfo_res['data']['skuCode']
        supplierId = supplierInfo_res['data']['supplierId']
        purchaseRatioQtyOwner = supplierInfo_res['data']['purchaseRatioQtyOwner']
        purchaseRatioQtySupplier = supplierInfo_res['data']['purchaseRatioQtySupplier']
        purchasePrice = supplierInfo_res['data']['purchasePrice']
        supplierSkuCode = supplierInfo_res['data']['supplierSkuCode']
        deliveryDay = 5
        supplierProductNo = supplierInfo_res['data']['supplierProductNo']
        supplierTagSize = supplierInfo_res['data']['supplierTagSize']
        public_data = ReadPublic(catalog=self.dir, key="update_supplierInfo")
        url = self.base_url + public_data.public_value("url").format(id)
        data = public_data.public_value("bar")
        data['skuId'] = skuId
        data['supplierId'] = supplierId
        data['purchaseRatioQtyOwner'] = purchaseRatioQtyOwner
        data['purchaseRatioQtySupplier'] = purchaseRatioQtySupplier
        data['purchasePrice'] = purchasePrice
        data['supplierSkuCode'] = supplierSkuCode
        data['deliveryDay'] = deliveryDay
        data['supplierProductNo'] = supplierProductNo
        data['supplierTagSize'] = supplierTagSize
        r = requests.put(url, headers=self.headers, json=data, stream=True, verify=False)
        return sku

    def sql_tracute_supplier(self):
        """
        清空erp_goods_operation.supplier、erp_goods_operation.supplier_sku_relation表
        """
        sku = self.update_supplierInfo()
        public_data = ReadPublic(catalog=self.dir, key="sql_insert_supplier")
        del_supplier = public_data.public_value('del_supplier')
        del_supplier_sku_relation = public_data.public_value('del_supplier_sku_relation')
        try:
            conn = pymysql.connect(host='172.28.188.107', port=3306, user='erp_test', passwd='localfSdCEi^qVwj44g$Rr',
                               db='erp_goods_operation')
            cur = conn.cursor()
            cur.execute(del_supplier)
            cur.execute(del_supplier_sku_relation)
            return sku
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()


    def sql_insert_supplier(self):
        """
        同步供货信息及供货关系的sql
        """
        sku = self.sql_tracute_supplier()
        public_data = ReadPublic(catalog=self.dir, key="sql_insert_supplier")
        insert_supplier = public_data.public_value('insert_supplier')
        insert_supplier_sku_relation = public_data.public_value('insert_supplier_sku_relation')
        if sku:
            try:
                conn = pymysql.connect(host='172.28.188.107', port=3306, user='erp_test',
                                       passwd='localfSdCEi^qVwj44g$Rr',
                                       db='erp_goods_operation')
                cur = conn.cursor()
                cur.execute(insert_supplier)
                cur.execute(insert_supplier_sku_relation)
                return sku
            except:
                self.singular = str(traceback.format_exc())
                outcome('red', self.singular)
                return self.singular
            finally:
                cur.close()
                conn.commit()
                conn.close()

    def sku_pda(self):
        """
        将sku调拨入库存
        """
        query_list = self.query_sourceType(sourceType=0).json()
        sku = query_list['data']['list'][0]['skuCode']
        #入库前的库存总量
        inventoryTotal = query_list['data']['list'][0]['inventoryTotal']
        public_data = ReadPublic(catalog=self.dir, key="sku_pda")
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['detailRequests'][0]['skuCode'] = sku
        requests.post(url, headers=self.headers, json=data, stream=True, verify=False)
        return sku, inventoryTotal

    def del_inventory_sql(self):
        """
        清空库存sql，清空前先将sku调拨入库存
        """
        pda = self.sku_pda()
        public_data = ReadPublic(catalog=self.dir, key="sql_inventory")
        del_inventory = public_data.public_value("del_inventory")
        try:
            conn = pymysql.connect(host='172.28.188.107', port=3306, user='erp_test', passwd='localfSdCEi^qVwj44g$Rr',
                               db='erp_goods_operation')
            cur = conn.cursor()
            cur.execute(del_inventory)
            return pda
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()

    def insert_inventory_sql(self):
        """
        清空库存表后，插入数据至库存
        """
        pda = self.del_inventory_sql()
        public_data = ReadPublic(catalog=self.dir, key="sql_inventory")
        insert_inventory = public_data.public_value("insert_inventory")
        if pda:
            try:
                conn = pymysql.connect(host='172.28.188.107', port=3306, user='erp_test',
                                       passwd='localfSdCEi^qVwj44g$Rr',
                                       db='erp_goods_operation')
                cur = conn.cursor()
                cur.execute(insert_inventory)
                return pda
            except:
                self.singular = str(traceback.format_exc())
                outcome('red', self.singular)
                return self.singular
            finally:
                cur.close()
                conn.commit()
                conn.close()


    def purchase_plan(self):
        """
        采购管理生成采购计划，
        """
        query_list = self.queryParameter()['data']['list'][0]
        sku = query_list['skuCode']
        intransitTotal = query_list['intransitTotal']
        warehouseId = ConfigYaml('warehouseId').base_config
        public_data = ReadPublic(catalog=self.dir, key="purchase_plan")
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['skuCodes'][0]['skuCode'] = sku
        data['warehouseId'] = warehouseId
        r = requests.post(url, headers=self.headers, json=data, stream=True, verify=False)
        return sku, intransitTotal

    def get_purchase_plan_id(self):
        """
        查询采购计划生成的planId(采购计划编号)
        前置条件生成采购计划
        """
        plan = self.purchase_plan()
        sku = plan[0]
        intransitTotal = plan[1]
        warehouseId = ConfigYaml('warehouseId').base_config
        public_data = ReadPublic(catalog=self.dir, key="get_purchase_plan_id")
        url = self.base_url + public_data.public_value("url").format(warehouseId)
        r = requests.get(url, headers=self.headers, stream=True, verify=False)
        result = r.json()
        if result['data']['list'][0]['skuNumbers'] > 0:
            id = result['data']['list'][0]['id']
            return id, sku, intransitTotal
        else:
            self.create_purchase_order()

    def purchase_plan_item(self):
        """该plainId 的详情页"""
        plan = self.get_purchase_plan_id()
        planId = plan[0]
        intransitTotal = plan[2]
        public_data = ReadPublic(self.dir, key="purchase_plan_item")
        url = self.base_url + public_data.public_value("url").format(planId)
        r = requests.get(url, headers=self.headers, stream=True, verify=False)
        return r, intransitTotal


    def purchase_batchNo(self):
        """生成采购批次号
        依赖get_purchase_plan_id
        """
        plan = self.purchase_plan_item()
        plan_list = plan[0].json()
        intransitTotal = plan[1]
        id = plan_list['data']['list'][0]['id']
        skuCode = plan_list['data']['list'][0]['skuCode']
        public_data = ReadPublic(catalog=self.dir, key="purchase_batchNo")
        url =self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['shippingAddressId'] = ConfigYaml('shippingAddressId').base_config
        data['planItemIds'] = [id]
        r = requests.put(url, headers=self.headers, json=data, stream=True, verify=False)
        result = r.json()
        batchNo = result['data']['batchNo']
        return batchNo, skuCode, intransitTotal

    def create_purchase_order(self):
        """
        生成采购订单
        """
        purchase_batch = self.purchase_batchNo()
        batchNo = purchase_batch[0]
        sku = purchase_batch[1]
        intransitTotal = purchase_batch[2]
        shippingAddressId = ConfigYaml('shippingAddressId').base_config
        public_data = ReadPublic(catalog=self.dir, key='create_purchase_order')
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['batchNo'] = batchNo
        data['shippingAddressId'] = shippingAddressId
        r = requests.put(url, headers=self.headers, json=data, stream=True, verify=False)
        return r, sku, intransitTotal

    def order_by_method(self, orderby):
        """备货参数列表，排序方式"""
        public_data = ReadPublic(catalog=self.dir, key="order_by_method")
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['warehouseId'] = ConfigYaml("warehouseId").base_config
        data['purchaseSaleStatus'] = ReadKeyWorld(self.dir).key_world_value("purchaseSaleStatus")
        data['orderBy'] = orderby
        print(url)
        print(data)
        r = requests.get(url, headers=self.headers, params=data, stream=True, verify=False)
        return r, url, data

    def purchaseSaleStatus(self, purchaseSaleStatus):
        """备货参数列表，购销状态查询,
           purchaseSaleStatus: 购销状态
        """
        public_data = ReadPublic(catalog=self.dir, key="purchaseSaleStatus")
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['warehouseId'] = ConfigYaml("warehouseId").base_config
        data['purchaseSaleStatus'] = purchaseSaleStatus
        r = requests.get(url, headers=self.headers, params=data, stream=True, verify=False)
        return r, url, data

    def beihuo_query(self, **kwargs):
        """
        备货参数列表，可变参数查询
        """
        readkw = ReadKeyWorld(self.dir)
        public_data = ReadPublic(catalog=self.dir, key="beihuo_query")
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['warehouseId'] = ConfigYaml("warehouseId").base_config
        data['purchaseSaleStatus'] = readkw.key_world_value("purchaseSaleStatus")
        data.update(kwargs)
        data['pageIndex'] = readkw.key_world_value("pageIndex")
        data['pageSize'] = readkw.key_world_value("pageSize")
        print(data)
        r = requests.get(url, headers=self.headers, params=data, stream=True, verify=False)
        print(r.json())
        return r, url, data

    def plm_list(self):
        """
        产品库列表查询
        publishStatus=20：SPU状态, 20可发布状态
        """
        public_data = ReadPublic(self.dir, key="plm_list")
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['publishStatus'] = ReadKeyWorld(self.dir).key_world_value("publishStatus")
        r = requests.post(url, headers=self.headers, json=data, stream=True, verify=False)
        return r

    def chooser_list(self):
        """选品人列表"""
        public_data = ReadPublic(self.dir, key="chooser_list")
        url = self.base_url + public_data.public_value("url")
        r = requests.get(url, headers=self.headers, stream=True, verify=False)

        name1 = jsonpath(r.json(), "$..data[?(@.name == '补旭东')]")[0]['name']
        name2 = jsonpath(r.json(), "$..data[?(@.name == '任涛')]")[0]['name']
        name3 = jsonpath(r.json(), "$..data[?(@.name == '周荣')]")[0]['name']
        name4 = jsonpath(r.json(), "$..data[?(@.name == '范天俊')]")[0]['name']
        name = name1 +","+ name2 +","+ name3 +","+ name4
        return name

    def owner_list(self):
        public_data = ReadPublic(self.dir, key="owner_list")
        url = self.base_url + public_data.public_value("url")
        r = requests.get(url, headers=self.headers, stream=True, verify=False)
        name1 = jsonpath(r.json(), "$..data[?(@.name == '补旭东')]")[0]['name']
        name2 = jsonpath(r.json(), "$..data[?(@.name == '任涛')]")[0]['name']
        name4 = jsonpath(r.json(), "$..data[?(@.name == '范天俊')]")[0]['name']
        name = name1 + "," + name2 + "," + "," + name4
        return name

    def del_sku_intransit_sql(self):
        """在途数据，清空在途数据库sku_intransit表"""
        pda = self.create_purchase_order()
        public_data = ReadPublic(catalog=self.dir, key="sku_intransit_sql")
        del_inventory = public_data.public_value("del_sku_intransit_sql")
        try:
            conn = pymysql.connect(host='172.28.188.107', port=3306, user='erp_test', passwd='localfSdCEi^qVwj44g$Rr',
                               db='erp_goods_operation')
            cur = conn.cursor()
            cur.execute(del_inventory)
            return pda
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()

    def insert_sku_intransit_sql(self):
        """在途数据，向商品运营的在数数据库的sku_intransit表插入数据"""
        pda = self.del_sku_intransit_sql()
        public_data = ReadPublic(catalog=self.dir, key="sku_intransit_sql")
        insert_inventory = public_data.public_value("insert_sku_intransit_sql")
        try:
            conn = pymysql.connect(host='172.28.188.107', port=3306, user='erp_test', passwd='localfSdCEi^qVwj44g$Rr',
                               db='erp_goods_operation')
            cur = conn.cursor()
            cur.execute(insert_inventory)
            return pda
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()






if __name__ == '__main__':

    GoodsRelatedData().beihuo_query(riskType=3)
    #GoodsRelatedData().get_purchase_plan_id()
    #GoodsRelatedData().purchase_plan()
    #GoodsRelatedData().insert_inventory_sql()
    #GoodsRelatedData().del_inventory_sql()
    #GoodsRelatedData().sku_pda()
    #GoodsRelatedData().sql_insert_supplier()
    #GoodsRelatedData().update_supplierInfo()
    #GoodsRelatedData().get_supplierInfo()
    #GoodsRelatedData().query_sourceType()
    #GoodsRelatedData().replenishment_import()
    #GoodsRelatedData().replenishment_export()
    #GoodsRelatedData().batchGenerate_by_ids()
    #GoodsRelatedData().purchase_list(purchase_status=1, sku='')
    #GoodsRelatedData().save_finalConfirmation()
    #GoodsRelatedData().submitRequisitionReview(5)
    #GoodsRelatedData().get_review_list(1, 0)
    #GoodsRelatedData().queryParameter()
    #GoodsRelatedData().get_review_list()
    #GoodsRelatedData().job_to_requisition_review(jobid='23')
    #GoodsRelatedData().job_manager_login()
    #GoodsRelatedData().updateParameter()
    #GoodsRelatedData().warehouse_list()

    #Login().write_token()
    #GoodsRelatedData().add_plm_product()
    #GoodsRelatedData().get_category_list()
    #GoodsRelatedData().add_plm_category()
    #GoodsRelatedData().get_attributes()
    #GoodsRelatedData().get_attributes()
    #GoodsRelatedData().add_attribute_to_category()
    #GoodsRelatedData().get_spu()
    #GoodsRelatedData().get_supplier()
    #GoodsRelatedData().infringement_review(spu='ytsasdfa2108180063')
    #GoodsRelatedData().infringement_review()
    #GoodsRelatedData().sample_to_auditor()
    #GoodsRelatedData().get_product_detail()
    #GoodsRelatedData().sample_check()
    #GoodsRelatedData().product_publish()